package com.topscomm.mpm.utils;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.pojo.MpmProjectSaleEntity;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Classname ContractConsumer
 * @Date 2022/3/8
 * @Created by jiangtao
 */
@Component
@RabbitListener(queues = "ltcMpmQueue")
public class MpmConsumer {
	@Autowired
	private MpmProjectService mpmProjectService;

	@Autowired
	private AmqpTemplate rabbitTemplate;
	@RabbitHandler
	public void receivedMpmMessage(String msg, Channel channel, Message messageTemp) throws Exception {
		try {
			Map<String,Object> message = JSONObject.parseObject(msg);
			String id = ConvertUtil.convertToString(message.get("sourceid"));
			String tablename = ConvertUtil.convertToString(message.get("tablename"));
			String projectcode = "";
			if(!MpmProjectEntity.tableName.equals(tablename)) {
				projectcode = ConvertUtil.convertToString(message.get("projectcode"));
			}
			String nowTime = "";
			//		if(message.containsKey("modifiedon")) {
			//			nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(ConvertUtil.convertToDate(message.get("modifiedon")));
			//		} else {
			//			nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			//		}
			nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

			StringBufferProxy sql = new StringBufferProxy();
			StringBufferProxy whereSql = new StringBufferProxy();
			List<Map<String,Object>> projectInfoList = new ArrayList<>();
			// 首先判定为线索，且为主表
			if (MpmProjectEntity.tableName.equals(tablename)) {
				whereSql.appendSingle("select projectsource,chanceclue from {0} where id = {1}", MpmProjectSaleEntity.tableName,id);
				projectInfoList = mpmProjectService.selectExecute(whereSql.toString());
			} else {
				projectcode = ConvertUtil.convertToString(message.get("projectcode"));
				whereSql.appendSingle(" select projectsource,chanceclue from {0} where id = (select id from {1} where projectcode = '{2}')",
						MpmProjectSaleEntity.tableName,MpmProjectEntity.tableName,projectcode);
				projectInfoList = mpmProjectService.selectExecute(whereSql.toString());
			}
			if(projectInfoList.size() > 0) {
				whereSql.clear();
				Map<String,Object> projectInfo = projectInfoList.get(0);
				String projectSource = ConvertUtil.convertToString(projectInfo.get("projectsource"));
				String chanceclue = ConvertUtil.convertToString(projectInfo.get("chanceclue"));
				String[] chanceclueArray = chanceclue.split(",");
				String chanceClueReal = Arrays.asList(chanceclueArray).stream().collect(Collectors.joining("','","'","'"));
				// 线索
				if("1".equals(projectSource)){
					sql.appendSingle(" update {0} set changetime = to_date('{1}','yyyy-mm-dd hh24:mi:ss') where code in ({2}) and manuscriptstatus = '9'"
							,"LtcLeadBackbone",nowTime,chanceClueReal);
					mpmProjectService.updateExecute(sql.toString());
				} else if("2".equals(projectSource)) {
					// 更新机会点
					sql.appendSingle(" update {0} set changetime = to_date('{1}','yyyy-mm-dd hh24:mi:ss') where code in ({2})  and manuscriptstatus = '9' "
							,"LtcChanceBackbone",nowTime,chanceClueReal);
					int a = mpmProjectService.updateExecute(sql.toString());
					// 更新线索
					sql.clear();
					sql.appendSingle("update {0} set changetime = to_date('{1}','yyyy-mm-dd hh24:mi:ss') where id in (select leadid from {2} where code in ({3}) and manuscriptstatus = '9' ) and manuscriptstatus = '9'",
							"LtcLeadBackbone",nowTime,"LtcChanceBackbone",chanceClueReal);
					mpmProjectService.updateExecute(sql.toString());
				}
			}
			channel.basicAck(messageTemp.getMessageProperties().getDeliveryTag(), false);
		}catch (Exception e) {
			channel.basicReject(messageTemp.getMessageProperties().getDeliveryTag(), false);
		}

	}
}
